from sqlalchemy.orm import Session
from models.models import LearnUserMaterialRecord
from schemas.record import UserRecordCreate, UserRecordResponse

def create_user_record(db: Session, record: UserRecordCreate):
    db_record = LearnUserMaterialRecord(material_id=record.material_id, page_number=record.page_number, user_id=record.user_id)
    db.add(db_record)
    db.commit()
    db.refresh(db_record)
    return db_record

def get_user_record(db: Session, user_id: int, material_id: int) -> UserRecordResponse:
    return db.query(LearnUserMaterialRecord).filter(
        LearnUserMaterialRecord.user_id == user_id,
        LearnUserMaterialRecord.material_id == material_id
    ).first()

def get_record_by_id(db: Session, record_id: int) -> UserRecordResponse:
    return db.query(LearnUserMaterialRecord).filter(LearnUserMaterialRecord.id == record_id).first()
    
def update_user_record(db: Session, record_id: int, page_number: int, current_user_id: int):
    record = db.query(LearnUserMaterialRecord).filter(LearnUserMaterialRecord.id == record_id, LearnUserMaterialRecord.user_id == current_user_id).first()
    if record:
        record.page_number = page_number
        db.commit()
        db.refresh(record)
        return record
    return None

def delete_user_record(db: Session, record_id: int, current_user_id: int):
    record = db.query(LearnUserMaterialRecord).filter(LearnUserMaterialRecord.id == record_id, LearnUserMaterialRecord.user_id == current_user_id).first()
    if record:
        db.delete(record)
        db.commit()
        return True
    return False
